<template>

  <div class="top">
    <div class="back">
      <BackSvg class="logout_line"/>
      <a href="/">回到首页</a>
    </div>
    <div class="title">
      问卷标题【
      <b>{{ surveyData.title }}</b>
      】 - 问卷创建时间 【
      <b>{{ surveyData.createTime }}</b>
      】
    </div>
  </div>

  <template v-if="isError">
    <div>请稍后再试</div>
  </template>

  <template v-else-if="loading">
    <div class="loading">
      <LoadingSvg />
    </div>
  </template>

  <template v-else>

    <div class="data-show">

      <div class="header">
        <span>共 {{ answerList.length }} 条数据</span>
        <div class="btn-box">
          <button @click="downSummary">导出汇总表格(csv)</button>
          <button @click="downOrigin">导出原始表格(csv)</button>
        </div>
      </div>

      <div class="table-wrapper">

        <div class="table-left">
          <table>

            <thead>
              <tr :style="{ height: theadH }">
                <th>
                  <p class="th-p">提交时间</p>
                </th>
              </tr>
            </thead>

            <tbody>
              <tr
                v-for="(answerLi, i) in answerList"
                :key="answerLi.id"
                data-answer-id="answerLi.id"
                :style="{ height: tbodyH[i] }">
                <td>
                  <p class="td-p">{{ answerLi.collectTime }}</p>
                </td>
              </tr>
            </tbody>

          </table>
        </div>

        <div class="table-main">
          <table>

            <thead>
              <tr ref="theadTr">
                <th v-for="(q, i) in questionList" :key="i">
                  <p class="th-p">
                    <span>{{ q }}</span>
                  </p>
                </th>
              </tr>
            </thead>

            <tbody>
              <tr
                v-for="answerLi in answerList"
                :key="answerLi.id"
                data-answer-id="answerLi.id"
                ref="tbodyTr">
                <td v-for="(answer, i) in answerLi.data" :key="i">
                  <p class="td-p"><span>{{ answer }}</span></p>
                </td>
              </tr>
            </tbody>

          </table>
        </div>

        <div class="table-right" >
          <table>

            <thead>
              <tr :style="{ height: theadH }">
                <th>
                  <p class="th-p">操作</p>
                </th>
              </tr>
            </thead>

            <tbody>
              <tr
                v-for="(answerLi, i) in answerList"
                :key="answerLi.id"
                data-answer-id="answerLi.id"
                :style="{ height: tbodyH[i] }">
                <td>
                  <div class="td-operate" v-permission="'edit'">
                    <button @click="editAnswer(answerLi.id)">编辑</button>
                    <button @click="delAnswer(answerLi.id)">删除</button>
                  </div>
                </td>
              </tr>
            </tbody>

          </table>
        </div>

      </div>

    </div>

    <!-- 编辑某份答案框 -->
    <div class="edit-answer" v-if="editing">
      <SurveyView
        :answerTime="editAnswerTime"
        :surveyId="editSurveyId"
        :answerId="editAnswerId"
        :questionsData="editQuestionsData"
        :oldAnswer="editOldAnswerData"
        @close="editing = false"
        @update="getData" />
    </div>

  </template>
</template>

<script>
import getStatData from './statData'
import getFormatSummary from './getFormatSummary'
import getFormatOrigin from './getFormatOrigin'
import delOneAnswer from '@/request/delOneAnswer'
import { defineAsyncComponent } from 'vue'
import {
  QUESTION_TYPE_MATRIX_RADIO,
  QUESTION_TYPE_MULTI,
  QUESTION_TYPE_SELECT,
  QUESTION_TYPE_SINGLE,
  QUESTION_TYPE_TEXT,
  QUESTION_TYPE_TEXTAREA,
} from '@/constants/default'

const SurveyView = defineAsyncComponent(() => import('./survey-view/index.vue'))

export default {
  components: { SurveyView },
  data() {
    return {
      theadH: '70px',
      tbodyH: ['70px'],
      tbody: null,
      loading: true,
      isError: false,
      questionList: [],
      answerList: [],
      surveyData: {},
      surveyTemplate: {},
      answersTemplate: {},
      originDownloading: false,
      summaryDownloading: false,

      editing: false,
      editAnswerTime: '',
      editSurveyId: '',
      editAnswerId: '',
      editQuestionsData: {},
      editOldAnswerData: {},
    }
  },
  methods: {
    setHeight() {
      setTimeout(() => {
        this.$refs.tbodyTr?.forEach((tr, i) => {
          const h = window.getComputedStyle(tr).height
          this.tbodyH[i] = Number.parseFloat(h) + 1 + 'px'
        })

        const h = window.getComputedStyle(this.$refs.theadTr).height
        this.theadH = Number.parseFloat(h) + 1 + 'px'
      })
    },
    async getData() {
      this.isError = false
      this.loading = true
      try {
        const statData = await getStatData()
        this.questionList = statData.questionList
        this.answerList = statData.answerList
        this.surveyData = statData.surveyData
        this.surveyTemplate = statData.surveyTemplate
        this.answersTemplate = statData.answersTemplate
        this.setHeight()
      } catch (error) {
        console.error('获取问卷和答案出错',error)
        this.isError = true
      } finally {
        this.loading = false
      }
    },
    async delAnswer(id) {
      try {
        if (window.confirm('确定删除?')) {
          await delOneAnswer(id)
          this.getData()
          this.$msg('成功删除', 'success')
        }
      } catch (error) {
        console.error(error)
        this.$msg('删除失败', 'error')
      }
    },
    formatQuestionsData() {
      /*
        [
          {
            id: 问题id,
            title: 问题描述,
            type: 问题类型,
            options: [ // 单选,多选,下拉,矩阵单选
              {
                id: 选项id,
                text: 选项描述,
              }
            ],
            subTitles: [ // 矩阵单选
              {
                id: 子问题id,
                title: 子问题描述,
              }
            ]
          }
        ]
      */

      // const qd = []
      // this.surveyData.questions.forEach(q => {
      //   qd.push({
      //     id: q.id,
      //     title: q.title,
      //     type: q.type,
      //     options: q.options,
      //     subTitles: q.subTitles,
      //   })
      // })
      return this.surveyData.questions
    },
    formatOldAnswersData() {
      /*
        {
            text问题id: '内容',
            textarea问题id: '内容',
            single问题id: '选项id',
            select问题id: '选项id',
            multi问题id: {
              '选项id': true
              '选项id': false
            }
            matrix问题id: {
              子问题id: '选项id',
              子问题id: '选项id',
            }
        }
      */
      const od = {}
      const i = this.answersTemplate.findIndex(a => a.id == this.editAnswerId)
      console.log('debugger: ', i)
      this.answersTemplate[i].answer.forEach(q => {
        if (
          q.type === QUESTION_TYPE_TEXT ||
          q.type === QUESTION_TYPE_TEXTAREA
        ) {
          od[q.id] = q.text
        } else if (
          q.type === QUESTION_TYPE_SELECT ||
          q.type === QUESTION_TYPE_SINGLE
        ) {
          od[q.id] = q.options[0]?.id
        } else if (q.type === QUESTION_TYPE_MATRIX_RADIO) {
          od[q.id] = {}
          q.groups.forEach(g => {
            od[q.id][g.id] = g.options[0]?.id
          })
        } else if (q.type === QUESTION_TYPE_MULTI) {
          // 初始化所有选项为 false
          const _i = this.surveyData.questions.findIndex(_q => _q.id === q.id)
          od[q.id] = {}
          this.surveyData.questions[_i].options.forEach(o => {
            od[q.id][o.id] = false
          })

          // 再将答案中有的改为 true
          q.options.forEach(o => {
            od[q.id][o.id] = true
          })
        }
      })
      return od
    },
    getCollectAnswerTime() {
      const i = this.answersTemplate.findIndex(a => a.id == this.editAnswerId)
      return this.answersTemplate[i].collect_time
    },
    async editAnswer(id) {
      this.editAnswerId = id
      this.editSurveyId = this.surveyData.id
      this.editAnswerTime = this.getCollectAnswerTime()
      this.editQuestionsData = this.formatQuestionsData()
      this.editOldAnswerData = this.formatOldAnswersData()
      this.editing = true
    },
    async downSummary() {
      if (this.summaryDownloading) {
        this.$msg('正在下载')
        return
      }
      this.summaryDownloading = true
      await getFormatSummary()
      this.summaryDownloading = false
    },
    async downOrigin() {
      if (this.originDownloading) {
        this.$msg('正在下载')
        return
      }
      this.originDownloading = true
      await getFormatOrigin()
      this.originDownloading = false
    },
  },
  mounted() {
    this.getData()
  },
}
</script>

<style lang="scss">
.loading {
  width: max-content;
  margin: 20px auto;
}

.top {
  width: 100%;
  height: 60px;
  padding: 16px;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-bottom: 1px solid #ddd;

  .back {
    flex: none;
    width: 85px;
    margin-right: 100px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;

    .logout_line {
      width: 20px;
      height: 20px;
    }

    &:hover .logout_line,
    &:hover a {
      color: #3d88ff;
      fill: #3d88ff;
    }
  }
}

.data-show {
  width: 1200px;
  padding: 16px;
  margin: 20px auto;
  border: 1px solid #e1e7f2;
  background-color: #fff;
  border-radius: 4px;

  .header {
    width: 100%;
    height: 40px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .btn-box {
      width: max-content;

      button {
        width: max-content;
        padding: 8px;
        margin-left: 16px;
        color: #333;
        box-sizing: content-box;
        border: 1px solid #ddd;
        border-radius: 4px;
        background-color: #fff;
        transition: 0.2s;
        cursor: pointer;

        &:hover {
          color: #3d88ff;
          border-color: #3d88ff;
        }
      }
    }
  }
}

.table-wrapper {
  width: 100%;
  position: relative;

  .table-main {
    width: calc(100% - 300px);
    margin-left: 200px;
    // border: 1px solid #ddd;
    overflow: auto;

    table {
      min-width: 100%;
      width: max-content;
      border-collapse: collapse;

      tr {
        border-bottom: 1px solid #33333333;
        background-color: #fff;

        &:nth-last-of-type(odd) {
          background-color: #f6f8fa;
        }
      }

      th {
        color: #999;
        padding: 0 20px;
      }

      td {
        padding: 10px 20px;
        text-align: center;
        color: #333;
      }

      .th-p,
      .td-p {
        max-width: 300px;
        min-height: 70px;
        margin: 10px auto;

        display: flex;
        justify-content: center;
        align-items: center;
      }

      th,
      td {
        position: relative;

        &::after {
          content: '';
          display: block;
          position: absolute;
          width: 0px;
          height: 80%;
          top: 10%;
          right: 0;
          box-shadow: 1px 0 0px 0.5px #f0f0f0;
        }
      }
    }
  }

  .table-left,
  .table-right {
    position: absolute;
    z-index: 2;
    top: 0;
    // border: 1px solid #ddd;

    table {
      min-width: 100%;
      width: max-content;
      border-collapse: collapse;

      tr {
        border-bottom: 1px solid #33333333;
        background-color: #fff;

        &:nth-last-of-type(odd) {
          background-color: #f6f8fa;
        }
      }
    }

    p {
      width: 100%;
      text-align: center;
    }
  }

  .table-left {
    left: 0;
    width: 200px;
    border-right: 2px solid #ddd;
  }

  .table-right {
    right: 0;
    width: 100px;
    border-left: 2px solid #ddd;

    .td-operate {
      display: flex;
      flex-direction: column;

      button {
        display: block;
        margin: 4px 8px;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
.edit-answer {
  width: 800px;
  height: 90vh;
  margin: auto;

  overflow: auto;
  box-shadow: 0 0 10px #aaa;
  background-color: #fff;

  position: fixed;
  top: 5vh;
  left: 0;
  right: 0;
  z-index: 99;
}
</style>
